package com.ocom.wxapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.dto.GetMealTimeDto;
import com.ocom.common.entity.card.EntityXfMealInfo;
import com.ocom.common.entity.card.EntityXfRecord;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.web.ConsTimeConfigOnShowRequest;
import com.ocom.common.request.web.ConsumeDetailPageRequest;
import com.ocom.common.request.wx.ConsumeDetailPageRequestQueryRequerst;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.AcpStateName;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.webapi.MealListVo;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.wxapi.client.HumanClientService;
import com.ocom.wxapi.client.PayConfigClientService;
import com.ocom.wxapi.client.XfRecordFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@PreAuthorize("hasRole('ROLE_WX')")
@RequestMapping("/ConsumeDetailPage")
@RestController
@Slf4j
public class ConsumeDetailPageController {


    @Autowired
    private XfRecordFeign xfRecordFeign;

    @Autowired
    private PayConfigClientService payConfigClientService;


    @Autowired
    private HumanClientService humanClientService;

    @PostMapping("/onShow")
    public Result ConsumeDetailPageOnShow(@Valid ConsumeDetailPageRequest consumeDetailPageRequest){
        JSONObject jsonObject= JSON.parseObject(JSON.toJSONString(consumeDetailPageRequest));
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        if(23 == yoCiUser.getRole()){
            jsonObject.put("deptId",yoCiUser.getDeptId());
        }
        Result result=xfRecordFeign.getConsumeDetail(jsonObject);
        if (result.getCode()==200){
            List<EntityXfMealInfo> listName=new ArrayList<>();
            JSONObject reJson=JSON.parseObject(JSON.toJSONString(result.getData()));
            List<EntityXfRecord> list=JSON.parseArray(JSON.toJSONString(reJson.get("list")),EntityXfRecord.class);
            for (EntityXfRecord entityXfRecord : list) {

                entityXfRecord.setSum(entityXfRecord.getRealMoney());
                entityXfRecord.setCharge(entityXfRecord.getChargeMoney());
                entityXfRecord.setSubsidy(entityXfRecord.getSubMoney());
                entityXfRecord.setBalance(entityXfRecord.getChargeBalance()+entityXfRecord.getSubBalance());
                for (EntityXfMealInfo entityXfMealInfo : listName) {
                    if (entityXfRecord.getMealNo().equals(entityXfMealInfo.getMealNo())){
                        entityXfRecord.setMealName(entityXfMealInfo.getMealName());
                    }
                }
                String paymentType= String.valueOf(entityXfRecord.getOpTypeDiff());
                String opType= String.valueOf(entityXfRecord.getOpType());
                int paymentTypes= Integer.parseInt(paymentType);
                entityXfRecord.setAmountType(AcpStateName.getConsName(entityXfRecord.getConsState(),paymentTypes,Integer.parseInt(opType)));
                entityXfRecord.setAmount(entityXfRecord.getConsMoney());
                entityXfRecord.setOrgOrderNo(entityXfRecord.getOrigOrderNo());
                entityXfRecord.setIsRefund(entityXfRecord.getIfRefund());
                entityXfRecord.setChargeBalance(entityXfRecord.getChargeBalance());
                entityXfRecord.setSubBalance(entityXfRecord.getSubBalance());
                entityXfRecord.setAccount(entityXfRecord.getAccountNo());
            }
            reJson.put("list",list);
            return ResultUtil.success(reJson);
        }
        return result;
    }

    @PostMapping("/query")
    public Result ConsumeDetailPageOnShow(@Valid ConsumeDetailPageRequestQueryRequerst consumeDetailPageRequestQueryRequerst){
        int pointId=-1;
        String startTime="";
        String stopTime="";
        if (!CommonUtil.isNull(consumeDetailPageRequestQueryRequerst.getPointName())){
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("companyId",consumeDetailPageRequestQueryRequerst.getCompanyID());
            jsonObject.put("summaryDate",consumeDetailPageRequestQueryRequerst.getSummaryDate());
            jsonObject.put("pointName",consumeDetailPageRequestQueryRequerst.getPointName());
            Result result=xfRecordFeign.getPointIdByNameFromRecord(jsonObject);
            if (result.getCode()==200){
                JSONObject object=JSON.parseObject(JSON.toJSONString(result.getData()),JSONObject.class);
                if (object.getInteger("pointId").compareTo(-1)==0){
                    return ResultUtil.error(ResultEnum.Err_4075);
                }
                pointId=object.getInteger("pointId");
            }else {
                return ResultUtil.error(ResultEnum.Err_4075);
            }
        }
        if (consumeDetailPageRequestQueryRequerst.getMealNo()!=0){
            if (consumeDetailPageRequestQueryRequerst.getStopTime()==null){
                String mealNo=String.valueOf(consumeDetailPageRequestQueryRequerst.getMealNo());

                ConsTimeConfigOnShowRequest request =new ConsTimeConfigOnShowRequest();
                request.setComId(consumeDetailPageRequestQueryRequerst.getCompanyID());
                request.setMealNo(mealNo);
                request.setPage(1);
                request.setSize(1);

//                Result result=payConfigClientService.GetMealTimeInfo(consumeDetailPageRequestQueryRequerst.getCompanyID(),
//                        mealNo,1,1);
                Result result=payConfigClientService.GetMealTimeInfo(request);
                if (result.getCode()==200){
                    JSONObject object=JSON.parseObject(JSON.toJSONString(result.getData()),JSONObject.class);
                    List<GetMealTimeDto> list =JSON.parseArray(JSON.toJSONString(object.get("list")),GetMealTimeDto.class);
                    for (GetMealTimeDto getMealTimeDto : list) {
                        startTime=getMealTimeDto.getBeginTime();
                        stopTime=getMealTimeDto.getEndTime();
                    }
                }
            }else {
                startTime=consumeDetailPageRequestQueryRequerst.getStartTime();
                stopTime=consumeDetailPageRequestQueryRequerst.getStopTime();
            }
        }else {
            startTime=" 00:00:00";
            stopTime=" 23:59:59";
        }

        if(!CommonUtil.isNull(consumeDetailPageRequestQueryRequerst.getStartTime())){
            startTime = " "+consumeDetailPageRequestQueryRequerst.getStartTime();
        }
        if(!CommonUtil.isNull(consumeDetailPageRequestQueryRequerst.getStopTime())){
            stopTime = " "+consumeDetailPageRequestQueryRequerst.getStopTime();
        }

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("comId",consumeDetailPageRequestQueryRequerst.getCompanyID());
        jsonObject.put("merchId",consumeDetailPageRequestQueryRequerst.getMachantID());
        jsonObject.put("deviceNo",consumeDetailPageRequestQueryRequerst.getDeviceNo());
        jsonObject.put("pointId",pointId);
        jsonObject.put("startTime",consumeDetailPageRequestQueryRequerst.getSummaryDate()+" "+startTime);
        jsonObject.put("endTime",consumeDetailPageRequestQueryRequerst.getSummaryDate()+" "+stopTime);
        jsonObject.put("page",consumeDetailPageRequestQueryRequerst.getPage());
        jsonObject.put("size",consumeDetailPageRequestQueryRequerst.getSize());

        log.info("获取报表参数 【{}】",jsonObject);

        Result result=xfRecordFeign.getConsumeDetail(jsonObject);
        if (result.getCode()==200){
            List<EntityXfMealInfo> listName=new ArrayList<>();
            //查询餐段名称
            Result mealList = payConfigClientService.GetMealNameInfo(consumeDetailPageRequestQueryRequerst.getCompanyID());
            if(mealList.getCode()==200){
                MealListVo mealListVo = JSON.parseObject(JSON.toJSONString(mealList.getData()),MealListVo.class);
                listName = mealListVo.getList();
            }
            JSONObject reJson=JSON.parseObject(JSON.toJSONString(result.getData()));
            List<EntityXfRecord> list=JSON.parseArray(JSON.toJSONString(reJson.get("list")),EntityXfRecord.class);
            for (EntityXfRecord entityXfRecord : list) {

                if (entityXfRecord.getPId() !=null  && entityXfRecord.getOpType()==22){
                    Result results = humanClientService.GetPersonInfo(consumeDetailPageRequestQueryRequerst.getCompanyID(),entityXfRecord.getPId());
                    if (results.getCode()==200){
                        if (results.getData() !=null){
                            EntityPersonnelInfo entityPersonnelInfo = JSON.parseObject(JSON.toJSONString(results.getData()), EntityPersonnelInfo.class);
                            if (entityPersonnelInfo.getPPhotoUrl2() !=null){
                                entityXfRecord.setPPhotoUrl2(entityPersonnelInfo.getPPhotoUrl2());
                            }else {
                                entityXfRecord.setPPhotoUrl2(entityPersonnelInfo.getPPhotoUrl());
                            }
                        }
                    }
                }

                entityXfRecord.setSum(entityXfRecord.getRealMoney());
                entityXfRecord.setCharge(entityXfRecord.getChargeMoney());
                entityXfRecord.setSubsidy(entityXfRecord.getSubMoney());
                entityXfRecord.setBalance(entityXfRecord.getChargeBalance()+entityXfRecord.getSubBalance());
                for (EntityXfMealInfo entityXfMealInfo : listName) {
                    if (entityXfRecord.getMealNo().equals(entityXfMealInfo.getMealNo())){
                        entityXfRecord.setMealName(entityXfMealInfo.getMealName());
                    }
                }
                String paymentType= String.valueOf(entityXfRecord.getOpTypeDiff());
                String opType= String.valueOf(entityXfRecord.getOpType());
                int paymentTypes= Integer.parseInt(paymentType);
                entityXfRecord.setAmountType(AcpStateName.getConsName(entityXfRecord.getConsState(),paymentTypes,Integer.parseInt(opType)));
                entityXfRecord.setAmount(entityXfRecord.getConsMoney());
                entityXfRecord.setOrgOrderNo(entityXfRecord.getOrigOrderNo());
                entityXfRecord.setIsRefund(entityXfRecord.getIfRefund());
                entityXfRecord.setChargeBalance(entityXfRecord.getChargeBalance());
                entityXfRecord.setSubBalance(entityXfRecord.getSubBalance());
                entityXfRecord.setAccount(entityXfRecord.getAccountNo());
            }
            reJson.put("list",list);
            return ResultUtil.success(reJson);
        }
        return result;
    }
}
